#include"globaldefine.h"


IDirect3D9 *g_pD3D = NULL;
IDirect3DDevice9 *g_pd3dDevice = NULL;

UASGame *g_pMyGame = NULL;

HRESULT InitD3D( HWND hWnd)
{
	if( NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)))
		return E_FAIL;

	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory(&d3dpp,sizeof(d3dpp));
	d3dpp.Windowed = TRUE;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;

	if( FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hWnd,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&d3dpp,&g_pd3dDevice)))
	{
		return E_FAIL;
	}

	//	startup game
	g_pMyGame = new UASGame();
	g_pMyGame->Init();

	return S_OK;
}

void CleanUp()
{
	//	cleanup game
	if(g_pMyGame != NULL)
	{
		g_pMyGame->CleanUp();

		delete g_pMyGame;
		g_pMyGame = NULL;
	}

	if(g_pd3dDevice != NULL)
		g_pd3dDevice->Release();
	
	if(g_pD3D != NULL)
		g_pD3D->Release();

}

void Tick(float deltaTime)
{
	g_pMyGame->Tick(deltaTime);		//	deal game logic
}

void Render()
{

	if( g_pd3dDevice )
	{
		g_pd3dDevice->Clear(0,0,D3DCLEAR_TARGET, D3DCOLOR_ARGB(255,255,255,255),1.0f,0);
		g_pd3dDevice->BeginScene();

		g_pMyGame->Render();				//	render game content

		g_pd3dDevice->EndScene();
		g_pd3dDevice->Present(0,0,0,0);
	}
}




LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
	switch( msg )
	{
	case WM_DESTROY:
		PostQuitMessage( 0 );
		return 0;
	}

    return DefWindowProc( hWnd, msg, wParam, lParam );
}

INT WINAPI WinMain(HINSTANCE hInst,HINSTANCE,LPSTR ,INT)
{
	WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L,
                GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
                L"ClassName", NULL };

	RegisterClassEx(&wc);

	HWND hWnd = CreateWindow(L"ClassName",L"UAS",WS_OVERLAPPEDWINDOW,
							g_iWindowPosX,g_iWindowPosY,g_iWindowSizeX,g_iWindowSizeY,
							GetDesktopWindow(),NULL,wc.hInstance,NULL);


	if(SUCCEEDED(InitD3D(hWnd)))
	{
		ShowWindow(hWnd,SW_SHOWDEFAULT);
		UpdateWindow(hWnd);

		MSG msg;
		ZeroMemory(&msg,sizeof(MSG));

		static float lastTime = (float)timeGetTime();
		while(msg.message != WM_QUIT)
		{
			if(PeekMessage(&msg,0,0,0,PM_REMOVE))
			{
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
			else
			{
				float currTime = (float)timeGetTime();
				float timeDelta = (currTime - lastTime)*0.001f;

				//	logic & display
				Tick(timeDelta);
				Render();

				lastTime = currTime;
			}
		}

		CleanUp();
	}

	return 0;
}